package com.caiyouxi.finance.service;

import com.alibaba.fastjson.JSONObject;
import com.caiyouxi.common.Constant;
import com.caiyouxi.common.bean.QueryParams;
import com.caiyouxi.common.bean.ResData;
import com.caiyouxi.common.cache.RedisService;
import com.caiyouxi.common.service.BaseService;
import com.caiyouxi.common.util.Log;
import com.caiyouxi.finance.mapper.CouponsMapper;
import com.caiyouxi.finance.model.CouponBatch;
import com.caiyouxi.finance.model.CouponType;
import com.caiyouxi.finance.model.Coupons;
import com.caiyouxi.finance.model.CouponsPayBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;


/**
 * 券信息
 * chensong
 */
@Service
public class CouponsService extends BaseService {
    
    @Autowired
    private CouponsMapper couponsMapper;
    @Autowired
    private CouponBatchService couponBatchService;
    @Autowired
    private CouponTypeService couponTypeService;
    @Autowired
    private RedisService redisService;

    public Coupons select_coupons(Integer couponsId){
        String key = "coupon_" + couponsId;
        Coupons c = (Coupons) redisService.get(key);
        if(c == null){
            c = couponsMapper.select_coupons(couponsId);
            redisService.set(key,c);
        }
        return c;
    }

    public void add_coupons(Coupons coupons){
        couponsMapper.add_coupons(coupons);
        Log.d("保存券信息结束");
    }

    public void update_coupons(Coupons coupons){
        couponsMapper.update_coupons(coupons);
    }

    public void delete_coupons(Coupons coupons){
        couponsMapper.delete_coupons(coupons);
    }
    
    public JSONObject getJsonByBean(Coupons coupons){
        JSONObject json = new JSONObject();
        json.put("id", coupons.getId());
        return json;
    }
    
    //获取所有的券信息
    public List<Coupons> get_coupons_list(){
        return couponsMapper.get_coupons_list();
    }

    //获取所有有效的券信息fund_type该券可以用在什么样的资金用途上
    public List<Coupons> get_coupons_usefull_list(CouponsPayBean bean){
        HashMap<String, Object> map = new HashMap();
        map.put("date", new Date());//当前时间，过滤失效或未生效
        map.put("fund_type", bean.getFund_type());
        map.put("bind_user_id",bean.getUser_id());
        return couponsMapper.get_coupons_usefull_list(map);
    }

    /**
     * 券校验
     */
    @Transactional
    public boolean check_coupons(Coupons coupons,String fund_type){
        if(coupons == null){
            Log.d("券不存在");
            return false;
        }
        //先判断券批次是否可用
        CouponBatch couponBatch = couponBatchService.select_coupon_batch(coupons.getBatch_id());
        if(couponBatch == null){
            Log.d("券批次不存在");
            return false;
        }
        if(!couponBatchService.check_coupon_batch(couponBatch,fund_type)){
            //券批次的状态不可用
            Log.d("券批次不可用");
            return false;
        }
        Date date = new Date();//当前时间
        if(!Constant.COUPONS_STATUS_NORMAL.equals(coupons.getStatus())){
            //券的状态非可用
            Log.d("券的状态不可用");
            return false;
        }
        if(date.after(coupons.getExpire_time())){
            //不在券的有效期内
            Log.d("券已失效");
            //更新状态为已过期
            if(Constant.COUPONS_STATUS_NORMAL.equals(coupons.getStatus()) || Constant.COUPONS_STATUS_BINDED.equals(coupons.getStatus())){
                coupons.setStatus(Constant.COUPONS_STATUS_EXPIRED);//已过期EXPIRED
                couponsMapper.update_coupons(coupons);
            }
            return false;
        }
        if(date.before(coupons.getStart_time())){
            //不在券的有效期内
            Log.d("券未生效");
            return false;
        }        
        return true;
    }

    /**
     * 根据交易流水更新券状态
     */
    public void update_coupons_by_trade_id(Integer finance_trade_details_id,String status){
        HashMap<String,Object> map = new HashMap();
        map.put("trade_id",finance_trade_details_id);
        map.put("status",status);
        couponsMapper.update_coupons_by_trade_id(map);
    }

    /**
     * 检验券是否可以混用
     */
    public boolean check_both_coupons(String[] coupons_ids,String key){
        //获取对应的券种类信息
        List<CouponType> coupontypes = couponTypeService.select_coupon_type_by_coupons_ids(coupons_ids,key);
        CouponType ct = null;
        boolean flag = false;
        int size = 0;
        for(CouponType coupontype : coupontypes){
            if(coupontype.getCombinations() != null){
                String[] couponts = coupontype.getCombinations().split("|");
                for(String coupont : couponts){
                    if(coupont != null && !"".equals(coupont)){
                        ct = couponTypeService.select_coupon_type(Integer.valueOf(coupont));
                        if(ct.getCombinations() != null){
                            String[] cts = ct.getCombinations().split("|");
                            for(String ct_id : cts){
                                if(ct_id.equals(coupontype.getId())){
                                    size ++;//可以混用
                                }
                            }
                        }
                    }
                }
            }
            flag = size == coupontypes.size();
        }
        return flag;
    }

    /**
     * 校验对应款项券信息并使用
     * @param fund_type 对应款项
     */
    public String[] check_coupons(String couponsids, String fund_type){
        if(!StringUtils.isEmpty(couponsids)){
            String[] coupons_ids = couponsids.split(",");
            //校验coupons_ids是否可以混用
            boolean cbc = check_both_coupons(coupons_ids,fund_type);
            if(!cbc){
                //券不可以混用——不享受券优惠抵扣
                return null;
            }
            return coupons_ids;
        }
        return null;
    }

    /**
     * 分页查询
     * @author wushihao create on 2017-11-28
     * */
    public ResData select_coupons_list(Coupons bean){
        QueryParams pageList = new QueryParams();
        if (bean.getPage_size() == 0){
            bean.setPage_size(Integer.parseInt(redisService.get("sys.pagesize").toString()));
        }
        pageList.setPage(bean.getPage());
        pageList.setPage_size(bean.getPage_size());
        pageList.setList(couponsMapper.select_coupons_list(bean));
        pageList.setTotal(couponsMapper.coupons_list_counts(bean));
        return success(pageList);
    }
    /**
     * @author wushihao
     * 更新(查看返回值以确定是否更新完毕)
     * */
    @Transactional
    public ResData update_coupons_override(Coupons bean){
        return success(couponsMapper.update_coupons(bean));
    }

}
